package com.naiterui.ehp.bs.patient.service.impl;

import cn.hutool.extra.servlet.ServletUtil;
import com.naiterui.ehp.bp.domain.Hospital;
import com.naiterui.ehp.bp.support.exception.BusinessException;
import com.naiterui.ehp.bp.support.exception.ResponseVO;
import com.naiterui.ehp.bp.utils.net.RestHttpUtil;
import com.naiterui.ehp.bs.patient.dao.IHospitalDao;
import com.naiterui.ehp.bs.patient.feign.IDoctorFeignClient;
import com.naiterui.ehp.bs.patient.service.IHospitalService;
import com.naiterui.ehp.bs.patient.utils.ConfigKeyUtil;
import com.naiterui.ehp.bs.patient.utils.cache.BaseParamCacheUtil;
import com.naiterui.ehp.bs.patient.utils.ip.LbsUtil;
import com.naiterui.ehp.bs.patient.vo.common.CityVO;
import com.naiterui.ehp.bs.patient.vo.common.HospitalVO;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.stereotype.Service;

/**
 * 医院接口实现类
 * <P>File name : HospitalService.java </P>
 * <P>Author : NTR.Amber </P>
 * <P>Date : 2015年9月11日 </P>
 */
@Service
public class ApHospitalServiceImpl implements IHospitalService {

    private static final Logger LOGGER = LoggerFactory.getLogger(ApHospitalServiceImpl.class);

    @Autowired
    private IHospitalDao hospitalDao;

    @Autowired
    private IDoctorFeignClient doctorFeignClient;

    @Override
    public List<HospitalVO> getHospitalList(Integer cityId, String name) {
        List<Integer> cityIds = new ArrayList<>();
        cityIds.add(cityId);
        CityVO city = BaseParamCacheUtil.getCityFromRedis(cityId);
        if (city != null) {
            // 获取当前城市所有子类id
            cityIds.addAll(BaseParamCacheUtil.getChildCityIds(city));
            // } else {
            // TODO：缓存里没有，从数据库查询
        }

        List<Hospital> hospitalList = hospitalDao.getHospitalList(cityIds, name);
        List<HospitalVO> voList = new ArrayList<>();
        for (Hospital hpt : hospitalList) {
            HospitalVO vo = new HospitalVO();
            BeanUtils.copyProperties(hpt, vo);
            voList.add(vo);
        }
        return voList;
    }

    @Override
    public Hospital getHospitalById(Integer id) {
        return hospitalDao.get(id);
    }

    @Override
    public String searchHospitals(String keyword) throws BusinessException {
        // 配置文件获取搜索服务地址
        String searchUrl = ConfigKeyUtil.getString(ConfigKeyUtil.HOSPITAL_SEARCH_URL);
        // 参数处理
        // 拼接关键字
        try {
            searchUrl += URLEncoder.encode(keyword, "utf-8");
        } catch (Exception e) {
            // 关键字编码异常，返回空参数结果集
            LOGGER.error("---------- hospital search error keyword error {}", keyword, e);
        }
        // 远程调用
        return RestHttpUtil.get().url(searchUrl).executeData(new ParameterizedTypeReference<ResponseVO<String>>() {
        });
    }

    @Override
    public List<HospitalVO> searchByCity(String keyword, HttpServletRequest request) throws BusinessException {
        String cityName = LbsUtil.getCityByIP(ServletUtil.getClientIP(request));
        LOGGER.info("定位城市：cityName={}", cityName);
        return doctorFeignClient.searchHospitalByCity(cityName, keyword);
    }

    @Override
    public List<HospitalVO> searchByLocation(String keyword, String lat, String lng) throws BusinessException {
        String cityName = "";
        if(StringUtils.isNotBlank(lat) && StringUtils.isNotBlank(lng)){
            cityName = LbsUtil.getCityByLocation(lat, lng);
        }
        LOGGER.info("定位城市：cityName={}", cityName);
        return doctorFeignClient.searchHospitalByCity(cityName, keyword);
    }
}
